from django.template.loader import render_to_string
from django import template
from garetjax.pages.models import Page

register = template.Library()

def render_tree(parser, token):
    try:
        tag_name, startpage, template_name = token.split_contents()
    except ValueError:
        try:
            template_name = '"pages/tree.html"'
            tag_name, startpage = token.split_contents()
        except ValueError:
            try:
                startpage = None
                tag_name = token.split_contents()
            except ValueError:
                raise template.TemplateSyntaxError, "%r tag requires one ore two arguments" % token.contents.split()[0]
    
    return TreeRenderer(startpage, template_name)

class TreeRenderer(template.Node):
    def __init__(self, startpage, template_name):
        try:
            self.startpage = template.Variable(startpage)
        except TypeError:
            self.startpage = None
        
        self.template_name = template.Variable(template_name)
        
    def render(self, context):
        request = template.Variable('request').resolve(context)
        
        try:
            if self.startpage is None:
                startpage = None
                items = Page.objects.filter(parent__isnull=True)
            else:
                startpage = self.startpage.resolve(context)
            
                try:
                    startpage.save
                    items = startpage.subpages.all()
                except AttributeError:
                    if startpage is None:
                        items = Page.objects.filter(parent__isnull=True)
                    else:
                        startpage = Page.objects.get(title=startpage)
                        items = startpage.subpages.all()
        except (template.VariableDoesNotExist, Page.DoesNotExist):
            return ''
            
        c = template.RequestContext(request, {
            'pages': items,
            'page': startpage
        })
        
        return render_to_string(self.template_name.resolve(context), c)
        
register.tag('structure', render_tree)